package global

import (
	"context"
	blacklistoperationlogic "dfx_cmdb/cmdb-blacklist-rpc/internal/logic/blacklistoperation"
	"dfx_cmdb/cmdb-blacklist-rpc/internal/svc"

	"github.com/it512/xxl-job-exec"
	"github.com/zeromicro/go-zero/core/logc"
)

// func checkEnableStatus(ctx context.Context, s *svc.ServiceContext, blackName string) (*cmdbblacklist.CmdbCronjoblist, error) {
// 	newBlacklist := new(cmdbblacklist.CmdbCronjoblist)
// 	err := s.PDB.Where("cronjob_name = ?", blackName).First(newBlacklist).Error
// 	if err != nil {
// 		logc.Error(ctx, "查询黑名单状态失败")
// 		return nil, err
// 	}
// 	logc.Debugf(ctx, "打印%s:黑名单状态", blackName, newBlacklist)
// 	return newBlacklist, nil

// }

func SetEnableHaproxyBlackList(ctx context.Context, s *svc.ServiceContext) error {
	s.Exec.RegTask(svc.HaproxyBlackList, func(ctx context.Context, task *xxl.Task) error {
		logc.Infof(ctx, "开始执行任务: %s", svc.HaproxyBlackList)
		haproxyErrorList, err := blacklistoperationlogic.QueryClickHouseHaproxyTopIp(ctx, s)
		if err != nil {
			logc.Errorf(ctx, "查询haproxy黑名单数据失败: %v", err)
			return err
		}
		err = blacklistoperationlogic.RedisSetHaproxyBlacklist(ctx, s, haproxyErrorList)
		if err != nil {
			logc.Errorf(ctx, "写入haproxy黑名单数据到Redis失败: %v", err)
			return err
		}
		return nil
	})
	return nil

}
func SetEnableOpenrestyBlackList(ctx context.Context, s *svc.ServiceContext) error {
	s.Exec.RegTask(svc.OpenrestyBlackList, func(ctx context.Context, task *xxl.Task) error {
		logc.Infof(ctx, "开始执行任务: %s", svc.OpenrestyBlackList)
		return nil
	})
	return nil

}
func SetEnableEBPFBlackList(ctx context.Context, s *svc.ServiceContext) error {
	s.Exec.RegTask(svc.EBPFBlackList, func(ctx context.Context, task *xxl.Task) error {
		logc.Infof(ctx, "开始执行任务: %s", svc.EBPFBlackList)
		return nil
	})
	return nil

}

// InitCronJob 初始化所有启用的黑名单定时任务
func InitCronJob(ctx context.Context, s *svc.ServiceContext) error {
	err := SetEnableHaproxyBlackList(ctx, s)
	if err != nil {
		logc.Errorf(ctx, "注册 Haproxy 黑名单失败: %v", err)
	}
	err = SetEnableOpenrestyBlackList(ctx, s)
	if err != nil {
		logc.Errorf(ctx, "注册 Openresty 黑名单失败: %v", err)
	}
	err = SetEnableEBPFBlackList(ctx, s)
	if err != nil {
		logc.Errorf(ctx, "注册 EBPF 黑名单失败: %v", err)
	}
	return err
}
